package com.liujit.auth.domain.result;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.liujit.auth.security.enums.PwdEncoderType;
import com.liujit.common.constants.GlobalConstant;
import com.liujit.upms.domain.model.SysUser;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: liujun
 * @date: 2021/6/22 5:10 下午
 * @description: 登录用户信息
 */
@Data
@ApiModel(value = "OauthUser", description = "登录用户信息")
public class OauthUser implements UserDetails {

    @ApiModelProperty(value = "用户id")
    private Long userId;

    @ApiModelProperty(value = "用户机构code")
    private String orgCode;

    @ApiModelProperty(value = "账号")
    private String account;

    @ApiModelProperty(value = "密码")
    private String pwd;

    @ApiModelProperty(value = "是否启用")
    private Boolean enabled;

    @ApiModelProperty(value = "用户权限")
    private Collection<SimpleGrantedAuthority> authorities;

    public OauthUser(SysUser user, List<Long> roles) {
        this.setUserId(user.getId());
        this.setOrgCode(user.getOrgCode());
        this.setAccount(user.getAccount());
        this.setPwd(PwdEncoderType.BCRYPT.prefix() + user.getPwd());
        this.setEnabled(GlobalConstant.ENABLED_YES.equals(user.getEnabled()));
        if (CollectionUtil.isNotEmpty(roles)) {
            authorities = new ArrayList<>();
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(Convert.toStr(role))));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.pwd;
    }

    @Override
    public String getUsername() {
        return this.account;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
